package api

import (
	"RedWork/dao"
	"RedWork/util"
	"RedWork/util/errmsg"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

func GetDetail() gin.HandlerFunc {
	return func(c *gin.Context) {
		good_id := c.Query("good_id")
		all := dao.QueryPhoneAllParm(good_id)
		//c.JSON(200, gin.H{
		//	"选择颜色": dao.PhoneColorSt(good_id),
		//	"选择版本": dao.PhoneParameter(good_id),
		//})
		c.JSON(200, gin.H{
			"status": true,
			"data":   all,
		})
	}
}

func AddFocus() gin.HandlerFunc {
	return func(c *gin.Context) {
		status := true
		data := "success"
		uid, ok := c.Get("uid")
		token_code, _ := c.Get("token_code")
		if token_code.(int) != errmsg.SUCCSE {
			status = false
			data = errmsg.GetErrMsg(token_code.(int))
		} else {
			gid := c.PostForm("good_id")
			if !ok {
				status = false
				data = errmsg.GetErrMsg(errmsg.COOKIE_NOT_EXIST)
			}
			if status {
				err := dao.AddFocusGood(strconv.Itoa(uid.(int)), gid)
				if err != nil {
					if ok, _, code := util.ErrHandle(err); ok {
						if code == 1062 {
							status = false
							data = "关注信息已存在，请勿重复添加"
						} else {
							status = false
							data = errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
						}
					} else {
						status = false
						data = errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
					}
				}
			}
		}

		c.JSON(200, gin.H{
			"status": status,
			"data":   data,
		})
	}
}

func QueryFocusGood() gin.HandlerFunc {
	return func(c *gin.Context) {
		status := true
		uid, _ := c.Get("uid")
		token_code, _ := c.Get("token_code")
		if token_code != errmsg.SUCCSE {
			status = false
			c.JSON(200, gin.H{
				"status": false,
				"data":   errmsg.GetErrMsg(token_code.(int)),
			})
			c.Abort()
			return
		} else {
			data := dao.QueryFocusGood(uid.(int))
			c.JSON(200, gin.H{
				"status": status,
				"data":   data,
			})
		}
	}
}

func DeleteFocusGood() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("IF ENT?")
		status := true
		data := "success"
		uid, _ := c.Get("uid")
		token_code, _ := c.Get("token_code")
		if token_code != errmsg.SUCCSE {
			status = false
			c.JSON(200, gin.H{
				"status": false,
				"data":   errmsg.GetErrMsg(token_code.(int)),
			})
			c.Abort()
			return
		}
		fmt.Println("uid= ", uid)
		gid := c.PostForm("good_id")
		err := dao.DeleteFocusGood(strconv.Itoa(uid.(int)), gid)
		if err != nil {
			fmt.Println(err)
			status = false
			if err.Error() == "no result" {
				data = errmsg.GetErrMsg(errmsg.PARM_NOT_RIGHT)
			} else {
				data = "DeleteFocusGood未知错误"
			}
		}
		c.JSON(200, gin.H{
			"status": status,
			"data":   data,
		})
	}
}
